/*
 * @Autor: Ruohong Yu
 * @Date: 2023-03-31 15:56:52
 * @Description: file content
 * @FilePath: \ebookd:\program\vsc\ebook\node-ebook\router_handler\user.js
 */
const bcrypt = require('bcryptjs')
const cryptoaes = require('../utils/cryptoforaes')
const jwt = require('jsonwebtoken')
const config = require('../bin/const')
// 注册新用户的处理函数
exports.register = (req, res) => {
  const userinfo = req.body
  const sqlStr = 'select * from users where username=?'
  userinfo.password=cryptoaes.decrypt(userinfo.password)
  config.db.query(sqlStr, userinfo.username, (err, results) => {
    if (err) {
      return res.send({ status: 1, message: err.message })
    }
    // 用户名被占用
    if (results.length > 0) {
      return res.send({ status: 2, message: '用户名被占用，请更换其他用户名！' })
    }
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    const sql = 'insert into users set ?'
    config.db.query(sql, { username: userinfo.username, password: userinfo.password, email:userinfo.email }, (err, results) => {
      if (err) return res.send({ status: 1, message: err.message })
      if (results.affectedRows !== 1) return res.send({ status: 1, message: '注册用户失败，请稍后再试！' })
      res.send({ status: 0, message: '注册成功！' })
    })
  })
}

// 登录的处理函数
exports.login = (req, res) => {
  const userinfo = req.body
  userinfo.password=cryptoaes.decrypt(userinfo.password)
  const sql = `select * from users where username=?`
  config.db.query(sql, userinfo.username, (err, results) => {
    if (err) return res.send({ status: 1, message: err.message })
    if (results.length !== 1) return res.send({ status: 1, message: '登录失败' })

    // 判断密码是否正确
    const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
    if (!compareResult) return res.send({ status: 2, message: '密码错误' })

    const user = { ...results[0], password: '', user_pic: '' }
    // 对用户的信息进行加密，生成 Token 字符串
    const tokenStr = jwt.sign(user, config.myjwtkey.jwtSecretKey, { expiresIn: config.myjwtkey.expiresIn })

    res.send({
      status: 0,
      message: '登录成功！',
      username: userinfo.username,
      useremail: results[0].email,
      avatar: results[0].avatar,
      token:  'Bearer ' + tokenStr,
    })
  })
}
